﻿using Autofac;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Opc.Ua;
using SqlSugar;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Warehouse.Entites;
using Warehouse.IServices;
using Warehouse.IServices.Conveyorlines;
using Warehouse.IServices.TESinterface;
using Warehouse.Services.Repository;
using Warehouse.ViewModels.TESinterfaceDTO;
using WCS.Entities;
using WCS.Entities.Api;
using WCS.Entities.BulkStorage;
using WCS.Entities.Enum;
using WCS.Entities.TES;
using WCS.IServices;
using WCS.Services;
using WCS.ViewModels;
using WCS.ViewModels.TESinterfaceDTO;
using static Warehouse.Services.StorageServices;

namespace Warehouse.Services.Conveyorlines
{
	public class ConveyorServices : Repository<Device>, IConveyorIServices
	{
		private readonly Repository<Device> _stor;
		private readonly Repository<TransferPort> _transferPort;
		private readonly Repository<BulkStorage> buk;
		private readonly Repository<Material> mat;
		private readonly IDeviceManager _deviceManager;
		private readonly Repository<BOX> box;
		//private readonly TcpClientReadCode tcp;
		private readonly ILogger<ConveyorServices> logger;
		private readonly ILifetimeScope lifetimeScope;
		private readonly Thread conveyorCheckThread;
		private readonly Repository<Types> barcode;
		private readonly IPsCarServices TES;
		private readonly Repository<Siterelease> sit;
		private readonly IStorageServices storage;
		private readonly Repository<Redatport> port;
		private readonly Repository<WareHouse> hous;
		private readonly Repository<FeederSites> feed;
		private readonly Repository<Ianeway> aneway;
		private readonly Repository<Salver> sal;
		private readonly Repository<DispatchHandling> spat;





		//private readonly TCPIpServices _CPIpServices;

		public ConveyorServices(Repository<Device> stor, Repository<TransferPort> repository, IDeviceManager deviceManager, Repository<BulkStorage> buk, Repository<Material> mat, Repository<BOX> box, ILogger<ConveyorServices> logger, ILifetimeScope lifetimeScope, Repository<Types> barcode, IPsCarServices TES, Repository<Siterelease> sit, Repository<Redatport> port, Repository<WareHouse> hous, Repository<FeederSites> feed, Repository<Ianeway> aneway, Repository<Salver> sal, Repository<DispatchHandling> spat)
		{
			_stor = stor;
			_transferPort = repository;
			_deviceManager = deviceManager;
			this.buk = buk;
			this.mat = mat;
			this.box = box;
			this.barcode = barcode;
			this.logger = logger;
			this.lifetimeScope = lifetimeScope;
			//conveyorCheckThread = new Thread(CheckConveyor);
			//conveyorCheckThread.IsBackground = true;
			//conveyorCheckThread.Start();
			this.TES = TES;
			this.sit = sit;
			this.port = port;
			this.hous = hous;
			this.feed = feed;
			this.aneway = aneway;
			this.sal = sal;
			this.spat = spat;
		}

		/// <summary>
		/// 传输线检查线程，物料到特定位置后，需要做判断，确定下一步去向
		/// </summary>
		public async void CheckConveyor()
		{
			//while (true)
			//{
			try
			{
				//整托散托判断点
				var position = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
				//出入库口是否有料
				var positionInOut = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001" && i.Name.Contains("出入"));

				if (position != null && DeviceIsConned(position.DeviceId) && positionInOut != null && DeviceIsConned(positionInOut.DeviceId))
				{
					var res1 = position?.BelongDevice.Operation.ReadInt16("490");

					//出入库前的停止点判断（位置2）
					var outOrPutStoragePort = position?.BelongDevice.Operation.ReadInt16("350");

					//拆垛位置是否有料以及任务号
					var unloadRes = position?.BelongDevice.Operation.ReadInt16("410");
					var unloadMissionRes = position?.BelongDevice.Operation.ReadInt32("418");

					//拆垛buffer位置1是否有料
					var unloadBuffer1Res = position?.BelongDevice.Operation.ReadInt16("420");
					var unloadBuffer1MissionRes = position?.BelongDevice.Operation.ReadInt32("428");

					//拆垛buffer位置2是否有料
					var unloadBuffer2Res = position?.BelongDevice.Operation.ReadInt16("380");
					var unloadBuffer2MissionRes = position?.BelongDevice.Operation.ReadInt32("388");

					var positionInOutRes = positionInOut?.BelongDevice.Operation.ReadInt16("370");

					//码垛位置是否有料以及任务号
					var loadRes = position?.BelongDevice.Operation.ReadInt16("450");
					var loadMissionRes = position?.BelongDevice.Operation.ReadInt32("458");

					//码垛buffer位置1是否有料
					var loadBuffer1Res = position?.BelongDevice.Operation.ReadInt16("460");
					var loadBuffer1MissionRes = position?.BelongDevice.Operation.ReadInt32("468");

					//码垛buffer位置2是否有料
					var loadBuffer2Res = position?.BelongDevice.Operation.ReadInt16("470");
					var loadBuffer2MissionRes = position?.BelongDevice.Operation.ReadInt32("478");

					//读贴标完成
					var biao = position?.BelongDevice.Operation.ReadInt16("300");
					var biao1MissionRes = position?.BelongDevice.Operation.ReadInt32("308");

					//提升机门口
					var Ti1 = position?.BelongDevice.Operation.ReadInt16("310");
					var Ti2 = position?.BelongDevice.Operation.ReadInt16("316");
					var Ti1MissionRes = position?.BelongDevice.Operation.ReadInt32("318");

					//散库线体
					var san1 = position?.BelongDevice.Operation.ReadInt16("730");
					var san1MissionRes = position?.BelongDevice.Operation.ReadInt32("738");

					// 扫码是否有承载
					var scan = position?.BelongDevice.Operation.ReadInt16("730");
					var SJob = position?.BelongDevice.Operation.ReadInt16("736");

					//小线体
					var dan = position.BelongDevice.Operation.ReadInt16("530");

					//二期入库
					var lirably = position?.BelongDevice?.Operation.ReadInt16("3760");
					var twoStorage = position?.BelongDevice?.Operation.ReadInt32("3768");
					var lirably1 = position?.BelongDevice?.Operation.ReadString("6560", 7);

					#region 一期入库口

					// 获得料口
					var oneTransPort = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11059");
					// 读取承载
					var onelirably = oneTransPort?.BelongDevice?.Operation.ReadInt16("110");
					// 读取任务号
					var oneJobNumber = oneTransPort?.BelongDevice.Operation.ReadInt32("118");

					#endregion

					//送空托盘
					var oneCar = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11059");
					var oneCar1 = oneCar?.BelongDevice?.Operation.ReadInt16("100");
					var oneCar2 = oneCar?.BelongDevice?.Operation.ReadInt32("108");
					var lisrty = position.BelongDevice?.Operation.ReadInt16("3766");
					var lisrty2 = position.BelongDevice?.Operation.ReadInt16("106");

					#region 一期入库

					if (onelirably != null && onelirably.Value == 1 && oneTransPort != null && DeviceIsConned(oneTransPort.DeviceId))
					{
						var palletNumber = oneTransPort.BelongDevice?.Operation.ReadString("6560", 8);
						if (palletNumber != null && !string.IsNullOrEmpty(palletNumber.Value))
						{
							logger.LogInformation($"一期入库口，线体任务读取托盘号：{palletNumber}");
							var materialInfo = mat.Query().FirstOrDefault(x => x.Palletnumber.Trim() == palletNumber.Value.Trim());
							if (materialInfo != null && oneJobNumber != null && oneJobNumber.Value == 123)
							{
								logger.LogInformation($"一期入库口，materialInfo托盘号：{materialInfo.Palletnumber}");
								// 获取任务信息
								var materialType = GetMaterialTypeByMission(oneJobNumber.Value, 0, materialInfo.Palletnumber);
								if (materialType != null && materialType.PalletNumber == materialInfo.Palletnumber)
								{
									var newJobNumber = NewJobNumber(materialType.JobNumbell, materialType.PalletNumber);
									if (newJobNumber > 0)
									{
										logger.LogInformation($"新的任务号：{newJobNumber}");
										oneTransPort.BelongDevice?.Operation.Write("114", (short)newJobNumber);
										Task.Delay(TimeSpan.FromSeconds(2));
										oneTransPort.BelongDevice?.Operation.Write("112", (short)11058);
									}
								}
							}
						}

						// 读取叉车放回前一个位置
						var mission = oneTransPort.BelongDevice?.Operation.ReadInt32("108");
						if (mission != null && mission.Value > 0)
						{
							var salverInfo = new Salver
							{
								warehouseID = "HETU",
								requestID = "86f3ebf3-1ba4-4ccc1",
								clientCode = "WCS",
								stationCode = "A1058",
								podID = DateTime.Now.ToString("MMddHHssmm"),
								layoutID = "513611347175407640",
							};
							var jobInfo = GetMaterialTypeByMission(mission.Value, 3);
							if (jobInfo != null)
							{
								if (string.IsNullOrEmpty(jobInfo.RobotJobCode))
								{
									jobInfo.RobotJobCode = salverInfo.podID;
									barcode.Context.Updateable(jobInfo).UpdateColumns(i => new { i.RobotJobCode }).ExecuteCommand();
									sal.Add(salverInfo);
								}
								else
								{
									var salverInfo1 = sal.Query().FirstOrDefault(i => i.podID == jobInfo.RobotJobCode);
									if (salverInfo1 != null)
									{
										// 通知四向车接的目标点
										var res = TES.occupyStation(salverInfo1);
										var resultInfo = JsonConvert.DeserializeObject<TESCreateJobDto>(res);
										logger.LogInformation($"响应结果：{JsonConvert.SerializeObject(resultInfo)}");

										if (resultInfo != null && resultInfo.returnCode == 0 && resultInfo.returnUserMsg.Contains("成功"))
										{
											logger.LogInformation($"1111111111111111");
											var Tes = new DispatchHandlingDTO()
											{
												warehouseID = "HETU",
												requestID = "86f3ebf3-1ba4-4ccc1",
												clientCode = "WCS",
												desType = 5,
												srcType = 1,
												podID = salverInfo1.podID,
												priority = 3,
												bizID = DateTime.Now.ToString("ddHHmmss"),
												desExt = new Dictionary<string, int>()
													{
														{ "unload", 1 }
													},
												bizExt = new Dictionary<string, string>()
													{
														{ "bizType", "out" }
													},
												desStationCodes = "A1036"
											};

											var materialInfo = mat.Query().FirstOrDefault(i => i.MaterialNumber == jobInfo.MaterialNamber);
											if (positionInOut != null && !positionInOut.IsFull &&
												positionInOut.CurrentNumber == 0 && positionInOutRes != null &&
												positionInOutRes.Value == 2 && materialInfo != null && (string.IsNullOrEmpty(materialInfo.Target) || materialInfo.Target == null))
											{
												positionInOut.CurrentNumber++;
												materialInfo.Target = positionInOut.Id;
												positionInOut.Palletnumber = materialInfo.Palletnumber;
												var materialUpdateIsOk = mat.Context.Updateable(materialInfo).UpdateColumns(i => new { i.Target }).ExecuteCommand();
												var updateIsOk = _transferPort.Context.Updateable(positionInOut).UpdateColumns(i => new { i.CurrentNumber, i.Palletnumber }).ExecuteCommand();
												if (updateIsOk > 0 && materialUpdateIsOk > 0)
												{
													logger.LogInformation("更新数据库成功");
													// 通知四向车送的目标点
													TES.newMovePodTasks(Tes);
													var tes1 = new DispatchHandling()
													{
														warehouseID = Tes.warehouseID,
														requestID = Tes.requestID,
														clientCode = Tes.clientCode,
														desType = Tes.desType,
														srcType = Tes.srcType,
														podID = Tes.podID,
														priority = Tes.priority,
														bizID = Tes.bizID,
														desStationCodes = Tes.desStationCodes,
														stare = false,
														Palletnumber = materialInfo.Palletnumber
													};
													spat.Add(tes1);
												}
											}
										}
										else
										{
											logger.LogInformation($"2222222222222");
											var materialInfo = mat.Query().FirstOrDefault(i => i.MaterialNumber == jobInfo.MaterialNamber);
											if (materialInfo != null && (string.IsNullOrEmpty(materialInfo.Target) || materialInfo.Target == null))
											{
												var robotJobCode = salverInfo1.podID;
												if (robotJobCode != jobInfo.RobotJobCode)
												{
													var isOk = barcode.Context.Updateable(jobInfo).UpdateColumns(i => new { i.RobotJobCode }).ExecuteCommand();
													logger.LogInformation($"Types更新数据:{isOk}");
												}
												logger.LogInformation($"333333333333");
												var Tes = new DispatchHandlingDTO()
												{
													warehouseID = "HETU",
													requestID = "86f3ebf3-1ba4-4ccc1",
													clientCode = "WCS",
													desType = 5,
													srcType = 1,
													podID = salverInfo1.podID,
													priority = 3,
													bizID = DateTime.Now.ToString("ddHHmmss"),
													desExt = new Dictionary<string, int>()
												{
													{ "unload", 1 }
												},
													bizExt = new Dictionary<string, string>()
												{
													{ "bizType", "out" }
												},
													desStationCodes = "A1036"
												};
												logger.LogInformation($"料口信息:positionInOut{positionInOut?.Id},{positionInOut?.CurrentNumber},{positionInOut?.IsFull}");
												if (positionInOut != null && !positionInOut.IsFull &&
													positionInOut.CurrentNumber == 0 && positionInOutRes != null &&
													positionInOutRes.Value == 2)
												{
													materialInfo.Target = positionInOut.Id;
													positionInOut.CurrentNumber++;
													positionInOut.Palletnumber = materialInfo.Palletnumber;
													var materialUpdateIsOk = mat.Context.Updateable(materialInfo).UpdateColumns(i => new { i.Target }).ExecuteCommand();
													var updateIsOk = _transferPort.Context.Updateable(positionInOut).UpdateColumns(i => new { i.CurrentNumber, i.Palletnumber }).ExecuteCommand();
													if (updateIsOk > 0 && materialUpdateIsOk > 0)
													{
														logger.LogInformation("更新数据库成功");
														// 通知四向车送的目标点
														TES.newMovePodTasks(Tes);
														var tes1 = new DispatchHandling()
														{
															warehouseID = Tes.warehouseID,
															requestID = Tes.requestID,
															clientCode = Tes.clientCode,
															desType = Tes.desType,
															srcType = Tes.srcType,
															podID = Tes.podID,
															priority = Tes.priority,
															bizID = Tes.bizID,
															desStationCodes = Tes.desStationCodes,
															stare = false,
															Palletnumber = materialInfo.Palletnumber
														};
														spat.Add(tes1);
													}
												}
											}
											var inform = ProccStation(!string.IsNullOrEmpty(jobInfo?.RobotJobCode) ? jobInfo.RobotJobCode : string.Empty);
											if (inform != null && inform.occupyStatus == 3)
											{
												logger.LogInformation($"444444444");
												jobInfo.IsComplete = true;
												barcode.Context.Updateable(jobInfo).UpdateColumns(i => new { i.IsComplete }).ExecuteCommand();
												oneCar?.BelongDevice.Operation.Write("132", (short)1);
												var Cont = new ContainerDTO
												{
													warehouseID = "HETU",
													requestID = "86f3ebf3-1ba4-4ccc1",
													clientCode = "WCS",
													stationCode = "A1058",
												};
												TES.releaseStation(Cont);
											}
										}
									}
								}
							}
						}

						if (positionInOut != null && positionInOutRes != null)
						{
							OutOrPutPort(positionInOut, positionInOutRes.Value > 0 ? 1 : 0);
						}
					}

					#endregion

					#region 二期入库口

					if (lirably.Value == 1 && lirably1 != null)
					{
						var list2 = mat.Query().FirstOrDefault(x => x.Palletnumber.Trim() == lirably1?.Value?.Trim());
						if (lirably.Value == 1 && list2 != null && twoStorage != null && twoStorage.Value == 123)
						{

							var materialType = GetMaterialTypeByMission(Convert.ToInt32(twoStorage.Value));
							logger.LogInformation($"当前有料状态，任务号：{twoStorage?.Value}");
							if (materialType.PalletNumber == list2.Palletnumber)
							{

								logger.LogInformation($"任务号：{twoStorage?.Value}，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
								position.BelongDevice.Operation.Write("3762", (short)11007);
								var newJobNumber = NewJobNumber(twoStorage.Value);
								if (newJobNumber > 0)
								{
									position.BelongDevice.Operation.Write("3764", (short)newJobNumber);
								}
							}
						}
					}

					#endregion

					#region 整托散托判断点
					if (res1 != null && res1.Value != 2)
					{
						//有料
						if (res1.Value == 1)
						{
							//读取任务号
							var missionRes = position.BelongDevice?.Operation.ReadInt32("498");
							logger.LogInformation($"当前有料状态，任务号：{missionRes?.Value}");
							//读到了任务号
							if (missionRes != null && missionRes.Value != 2)
							{
								//To do1：根据读到的任务号，判断是整托还是散托，然后分配去不同的位置，整托缠绕贴标，散托&空托盘，到位置2
								var materialType = GetMaterialTypeByMission(Convert.ToInt32(missionRes.Value), 3);

								//整托
								if (materialType != null && materialType.type == MaterialType.zhengtuo)
								{
									logger.LogInformation($"任务号：{missionRes?.Value}，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
									//去整托位置
									position.BelongDevice?.Operation.Write("492", (short)11028);
									var newJobNumber = NewJobNumber(missionRes.Value, materialType.PalletNumber);
									if (newJobNumber > 0)
									{
										position.BelongDevice?.Operation.Write("494", (short)newJobNumber);
									}
									logger.LogInformation($"当前物料为整托，对应类型：{materialType}");
								}
								//散托或者空托盘
								else
								{
									//去位置2
									var resultIok = position.BelongDevice?.Operation.Write("492", (short)11033);
									var newJobNumber = NewJobNumber(missionRes.Value, materialType.PalletNumber);
									if (newJobNumber > 0)
									{
										position.BelongDevice?.Operation.Write("494", (short)newJobNumber);
									}
									logger.LogInformation($"当前物料为散拖或者是空托盘，对应类型：{materialType},是否写值成功：{resultIok?.IsSucceed},{JsonConvert.SerializeObject(resultIok)}");
								}
								//To do2：如果是整托，对接贴标机
								//position1Mission = missionRes.Value;
								//position1Status = res1.Value;
							}
						}

					}
					#endregion

					#region 贴标完成到提升机门口

					if (biao != null && biao != null)
					{
						//有料
						if (biao.Value == 1)
						{
							//读取任务号
							var missionRes = position.BelongDevice?.Operation.ReadInt32("308");
							var missionRes1 = position.BelongDevice?.Operation.ReadInt32("3710");
							//读到了任务号
							if (missionRes != null && missionRes.Value != 2 && missionRes1.Value == 1)
							{
								//发到提升机门口给小车发信息
								position.BelongDevice?.Operation.Write("302", (short)11028);
								var newJobNumber = NewJobNumber(missionRes.Value);
								if (newJobNumber > 0)
								{
									position.BelongDevice?.Operation.Write("304", (short)newJobNumber);
								}
							}
						}
					}
					#endregion

					#region 出入库前的停止点判断（位置2）
					//上面是否有料
					if (outOrPutStoragePort != null && outOrPutStoragePort.Value != 2)
					{
						//有料
						if (outOrPutStoragePort.Value == 1)
						{
							//读取任务号
							var missionRes = position.BelongDevice?.Operation.ReadInt32("358");
							logger.LogInformation($"当前出入库前的停止点，读取任务后：{missionRes?.Value}");
							//读到了任务号，这次任务号跟上次不同，或者上次的任务号检查没通过，需要继续检查
							if (missionRes != null && missionRes.Value != 0)
							{
								//To do1：根据读到的任务号，判断是散托、空托盘，然后分配去不同的位置
								var materialType = GetMaterialTypeByMission(missionRes.Value, 3);

								//如果是散托，准备送往拆垛位置
								if (materialType != null && materialType.type == MaterialType.two)
								{

									logger.LogInformation($"任务号：{missionRes?.Value}，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
									//1.判断拆垛位置&缓存位置是否有料，全部没有料，送到拆垛位
									if (unloadRes?.Value == 2 && unloadBuffer1Res?.Value == 2 && unloadBuffer2Res?.Value == 2)
									{
										logger.LogInformation($"任务号：{missionRes?.Value}货送到拆垛位，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
										//送去拆垛位置，当前任务不用继续检查

										position.BelongDevice?.Operation.Write("352", (ushort)11041);
										var newJobNumber = NewJobNumber(missionRes.Value);
										if (newJobNumber > 0)
										{
											position.BelongDevice?.Operation.Write("354", (short)newJobNumber);
										}

									}
									//2.拆垛位置有料，判断缓存位是否有空余，有空余，送到缓存位
									else if (unloadRes?.Value == 1 && (/*unloadBuffer1Res?.Value == 2 ||*/ unloadBuffer2Res?.Value == 2))
									{
										//if (unloadBuffer1Res?.Value == 0)
										//{
										//	////logger.LogInformation($"任务号：{missionRes?.Value}货送去1号缓存位，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
										//	//送去1号缓存位置
										//	position2?.BelongDevice.Operation.Write("352", (short)11042);
										//	var newJobNumber = NewJobNumber(missionRes.Value);
										//	if (newJobNumber > 0)
										//	{
										//		position1?.BelongDevice.Operation.Write("354", (short)newJobNumber);
										//	}
										//}
										//else
										//{
										//送去2号缓存位置
										position.BelongDevice?.Operation.Write("352", (short)11037);
										var newJobNumber = NewJobNumber(missionRes.Value);
										if (newJobNumber > 0)
										{
											position.BelongDevice?.Operation.Write("354", (short)newJobNumber);
										}
										logger.LogInformation($"任务号：{missionRes?.Value}货送去2号缓存位，得到物料类型：{JsonConvert.SerializeObject(materialType)}");

										//}
									}
									//3.缓存位没有空余，入库
									else if (unloadRes?.Value == 1 && unloadBuffer1Res?.Value == 1 && unloadBuffer2Res?.Value == 1)
									{
										//准备入库，入库前需要检查
										//3.1.判断出入库位置有没有料，有料的话转3.2，没有料，直接送到出入库位置
										//3.2.出入库位置有料，等待下次检查
										if (positionInOutRes?.Value == 2)
										{
											logger.LogInformation($"任务号：{missionRes?.Value}货，没有空余缓存位直接入库，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
											//直接入库
											positionInOut?.BelongDevice.Operation.Write("352", (short)11036);
											var newJobNumber = NewJobNumber(missionRes.Value);
											if (newJobNumber > 0)
											{
												position.BelongDevice?.Operation.Write("354", (short)newJobNumber);
											}
										}
									}
								}
								//空托盘
								else if (materialType != null && materialType.type == MaterialType.three)
								{
									//1.判断码垛位置&空托盘缓存位置是否有料，全部没有料，送到码垛位
									if (loadRes?.Value == 2 && loadBuffer1Res?.Value == 2)
									{
										logger.LogInformation($"任务号：{missionRes?.Value}货，码垛位置&空托盘缓存位置全部没有料，送到码垛位，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
										//送去码垛位置，当前任务不用继续检查
										position.BelongDevice?.Operation.Write("352", (short)11046);
										var newJobNumber = NewJobNumber(missionRes.Value);
										if (newJobNumber > 0)
										{
											position.BelongDevice?.Operation.Write("354", (short)newJobNumber);
										}


									}
									//2.码垛位置有料，判断缓存位是否有空余，有空余，送到缓存位
									else if (loadRes?.Value == 1 && loadBuffer1Res?.Value == 2)
									{
										logger.LogInformation($"任务号：{missionRes?.Value}货，缓存位有空余，送到缓存位，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
										//送去空托盘缓存位置
										position.BelongDevice?.Operation.Write("352", (short)11047);
										var newJobNumber = NewJobNumber(missionRes.Value);
										if (newJobNumber > 0)
										{
											position.BelongDevice?.Operation.Write("354", (short)newJobNumber);
										}


									}
									//3.缓存位没有空余，入库
									else if (loadRes?.Value == 1 && loadBuffer1Res?.Value == 1)
									{
										//准备入库，入库前需要检查
										//3.1.判断出入库位置有没有料，有料的话转3.2，没有料，直接送到出入库位置
										//3.2.出入库位置有料，等待下次检查
										if (positionInOutRes?.Value == 2)
										{
											logger.LogInformation($"任务号：{missionRes?.Value}货，缓存位没有空余，送到库位，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
											//直接入库
											missionRes = position.BelongDevice?.Operation.ReadInt32("358");
											position.BelongDevice?.Operation.Write("352", (short)11036);
											var newJobNumber = NewJobNumber(missionRes.Value);
											if (newJobNumber > 0)
											{
												position.BelongDevice?.Operation.Write("354", (short)newJobNumber);
											}
											//var Station = new FeederSitesDTO
											//{
											//    warehouseID = "HETU",
											//    requestID = "86f3ebf3-1ba4-4ccc1",
											//    clientCode = "WCS",
											//    stationCode = "A1036",
											//};
											//TES.preOccupyStation(Station);
											//var model = new SalverDTO
											//{
											//    warehouseID = "HETU",
											//    requestID = "86f3ebf3-1ba4-4ccc1",
											//    clientCode = "WCS",
											//    stationCode = "A1036",
											//    podID = DateTime.Now.ToString("ddHHss"),
											//    layoutID = "513611347175407640",
											//};
											//var numbell = GetMaterialTypeByMission(missionRes.Value);
											//var bulkInfor = new AssignStorageViewModel
											//{
											//    MaterialNamber = numbell.MaterialNamber
											//};
											//var sty = await AssignStorage(bulkInfor);
											//var model1 = new IanewayDTO
											//{
											//    warehouseID = "HETU",
											//    requestID = "86f3ebf3-1ba4-4ccc1",
											//    clientCode = "WCS",
											//    desType = locations.StorageLocation,
											//    srcType = 1,
											//    podID = model.podID,
											//    priority = 3,
											//    bizID = DateTime.Now.ToString("ddHHss") + 1,
											//    replacePodTask = 0,
											//    desExt = new Dictionary<string, int>()
											//    {
											//         { "unload",1 }
											//    },
											//    desStorageID = sty.CrownPrincce,
											//};
											//TES.newMovePodTask(model1);

										}
									}
								}
							}
						}
					}
					#endregion

					#region 入库
					if (Ti1.Value != 0)
					{
						//有料
						if (Ti1.Value == 1)
						{
							//读取任务状态
							var missions = Ti2.Value;
							//读到了任务号
							if (missions != null && (missions == 2 || missions == 1))
							{
								var missions1 = Ti1MissionRes;
								//发到提升机门口给小车发信息

								var newJobNumber1 = NewJobNumber(missions1.Value);
								if (newJobNumber1 > 0)
								{


									position?.BelongDevice.Operation.Write("314", (short)newJobNumber1);
									Task.Delay(TimeSpan.FromSeconds(2));
									position?.BelongDevice.Operation.Write("312", (short)11029);

									var salmodel = new Salver
									{
										warehouseID = "HETU",
										requestID = "86f3ebf3-1ba4-4ccc1",
										clientCode = "WCS",
										stationCode = "1028",
										podID = DateTime.Now.ToString("MMddHHssmm"),
										layoutID = "513611347175407640",
									};
									var numbell = GetMaterialTypeByMission(newJobNumber1);
									if (string.IsNullOrEmpty(numbell.RobotJobCode))
									{
										numbell.RobotJobCode = salmodel.podID;
										await barcode.Context.Updateable<Types>(numbell).UpdateColumns(i => new { i.RobotJobCode }).ExecuteCommandAsync();
										sal.Add(salmodel);
									}

									var slverInfo = sal.Query().FirstOrDefault(i => i.podID == numbell.RobotJobCode);
									if (slverInfo != null)
									{
										TES.occupyStation(slverInfo);
										var bulkInfor = new AssignStorageViewModel
										{
											MaterialNamber = numbell.MaterialNamber
										};

										var lister = barcode.Query().Where(x => x.NewJobNumbell == newJobNumber1).FirstOrDefault();
										var materialinfo = mat.Query().FirstOrDefault(i => i.MaterialNumber == lister?.MaterialNamber);
										var sty = new WareHouse();
										if (string.IsNullOrEmpty(materialinfo?.StorageId))
										{
											sty = await AssignStorage(bulkInfor);
										}
										else
										{
											sty = hous.Query().FirstOrDefault(x => x.MaterialNamber == materialinfo?.MaterialNumber);
										}
										if (sty != null)
										{
											var model1 = new IanewayDTO
											{
												warehouseID = "HETU",
												requestID = "86f3ebf3-1ba4-4ccc1",
												clientCode = "WCS",
												desType = locations.StorageLocation,
												srcType = 1,
												podID = slverInfo.podID,
												priority = 3,
												bizID = DateTime.Now.ToString("ddHHss"),
												replacePodTask = 0,
												desExt = new Dictionary<string, int>()
												{
													 { "unload",1 }
												},
												desStorageID = sty.CrownPrincce,
											};
											TES.newMovePodTask(model1);
											var anemodel = new Ianeway
											{
												warehouseID = model1.warehouseID,
												requestID = model1.requestID,
												clientCode = model1.clientCode,
												desType = model1.desType,
												srcType = 1,
												podID = model1.podID,
												priority = model1.priority,
												bizID = model1.bizID,
												replacePodTask = model1.replacePodTask,
												desExt = JsonConvert.SerializeObject(model1.desExt),
												desStorageID = model1.desStorageID,
											};
											var informate = barcode.Query().Where(x => x.NewJobNumbell == missions1.Value).FirstOrDefault();
											var inform = ProccStation(!string.IsNullOrEmpty(informate?.RobotJobCode) ? informate.RobotJobCode : string.Empty);
											if (inform != null && inform.occupyStatus == 3)
											{
												var Cont = new ContainerDTO
												{
													warehouseID = "HETU",
													requestID = "86f3ebf3-1ba4-4ccc1",
													clientCode = "WCS",
													stationCode = "1028",
												};
												TES.releaseStation(Cont);
											}
										}
									}
								}
							}
						}
					}
					#endregion

					#region 拆垛位置状态监控
					//1.检查是否有托盘
					//2.拆垛位置没有托盘，到2.1，有托盘到2.2
					if (unloadRes != null && unloadRes.Value == 2 && unloadMissionRes != null && unloadMissionRes.Value == 0)
					{
						var positionInOutMissionRes = positionInOut?.BelongDevice.Operation.ReadInt32("378");
						//2.1 检查拆垛缓存位置是否有料，有的话，从缓存位置送到拆垛位置，没有的话，生成散托出库任务
						//if (unloadBuffer1Res?.Value == 1)
						//{
						//	//从缓存1位置送到拆垛位置
						//	logger.LogInformation($"任务号：{unloadBuffer1MissionRes.Value}，缓存1位置送到拆垛位置");
						//	positionUnloadBuffer1?.BelongDevice.Operation.Write("422", (short)11041);
						//	var newJobNumber = NewJobNumber(unloadBuffer1MissionRes.Value);
						//	if (newJobNumber > 0)
						//	{
						//		positionUnloadBuffer1?.BelongDevice.Operation.Write("424", (short)newJobNumber);
						//	}

						//}
						//else
						if (unloadBuffer2Res?.Value == 1)
						{
							//从缓存2位置送到拆垛位置
							logger.LogInformation($"任务号：{unloadBuffer2MissionRes}，缓存2位置送到拆垛位置");
							position.BelongDevice?.Operation.Write("382", (short)11041);
							var newJobNumber = NewJobNumber(unloadBuffer2MissionRes.Value);
							if (newJobNumber > 0)
							{
								position.BelongDevice?.Operation.Write("384", (short)newJobNumber);
							}


						}
						else
						{
							//生成散托出库任务
							logger.LogInformation($"任务号：{unloadMissionRes}，散库出库任务");
							//根据库位信息查找散拖送到A1036
							positionInOut?.BelongDevice.Operation.Write("372", (short)11007);
							var newJobNumber = NewJobNumber(positionInOutMissionRes.Value);
							if (newJobNumber > 0)
							{
								positionInOut?.BelongDevice.Operation.Write("374", (short)newJobNumber);
							}


						}
					}
					else
					{
						if (unloadMissionRes != null && unloadRes.Value != 2)
						{

							var materialType = GetMaterialTypeByMission(unloadMissionRes.Value, 3);

							if (materialType != null && materialType.type == MaterialType.two)
							{
								var list1 = barcode.Query();
								var sty = list1.FirstOrDefault(x => x.JobNumbell == materialType.JobNumbell || x.NewJobNumbell == materialType.NewJobNumbell);
								if (sty != null)
								{
									var stylist = mat.Query().FirstOrDefault(x => x.MaterialNumber == sty.MaterialNamber);
									if (stylist != null)
									{
										var res = stylist.MaterialName;
										if (res.Contains("210"))
										{
											//箱数
											await Conveyor(2, 24);
										}
										else
										{
											await Conveyor(1, 30);
										}
									}
								}
							}
							if (materialType != null)
							{
								var res = position.BelongDevice?.Operation.ReadInt16("410");
								var Fan = position.BelongDevice?.Operation.ReadInt16("3721");
								var Wan = position.BelongDevice?.Operation.ReadInt16("3719");
								if (Wan != null && Wan.Value != 0)
								{
									var bell = barcode.Query().FirstOrDefault(x => x.PalletNumber == materialType.PalletNumber);
									if (bell != null)
									{
										bell.type = MaterialType.three;
										var isOk = barcode.Update(bell);
										if (isOk)
										{
											position.BelongDevice?.Operation.Write("3713", (short)0);
											position.BelongDevice?.Operation.Write("3714", (short)0);
											position.BelongDevice?.Operation.Write("3717", (short)0);
										}
									}
								}
							}
							//2.2 检查托盘是空托盘还是散托，空托盘到2.2.1和2.2.2、2.2.3，散托盘，到2.2.4
							//空托盘
							if (materialType != null && materialType.type == MaterialType.three)
							{
								logger.LogInformation($"任务号：{unloadMissionRes}，得到物料类型：{JsonConvert.SerializeObject(materialType)}");
								//1.判断码垛位置&空托盘缓存位置是否有料，全部没有料，送到码垛位
								if (loadRes?.Value == 2 && loadBuffer1Res?.Value == 2)
								{
									//送去码垛位置，当前任务不用继续检查
									logger.LogInformation($"任务号：{unloadMissionRes}，送去码垛位置");
									position.BelongDevice?.Operation.Write("412", (short)11046);
									var newJobNumber = NewJobNumber(unloadMissionRes.Value);
									if (newJobNumber > 0)
									{
										position.BelongDevice?.Operation.Write("414", (short)newJobNumber);
									}
								}
								//2.码垛位置有料，判断缓存位是否有空余，有空余，送到缓存位
								else if (loadRes?.Value == 1 && loadBuffer1Res?.Value == 2)
								{
									//送去空托盘缓存位置
									logger.LogInformation($"任务号：{unloadMissionRes}，送去空托盘缓存位置");
									position.BelongDevice?.Operation.Write("412", (short)11047);
									var newJobNumber = NewJobNumber(unloadMissionRes.Value);
									if (newJobNumber > 0)
									{
										position.BelongDevice?.Operation.Write("414", (short)newJobNumber);
									}

								}
								//3.送到缠绕膜位置，准备入库
								else if (loadRes?.Value == 1 && loadBuffer1Res?.Value == 1)
								{
									//送到缠绕膜位置
									logger.LogInformation($"任务号：{unloadMissionRes}，送到缠绕膜位置");
									position.BelongDevice?.Operation.Write("412", (short)11007);
									var newJobNumber = NewJobNumber(unloadMissionRes.Value);
									if (newJobNumber > 0)
									{
										position.BelongDevice?.Operation.Write("414", (short)newJobNumber);
									}

								}
							}
							//散托
							else if (materialType != null && materialType.type == 0)
							{
								//2.2.4 调用散库接口，判断是否有散库出库任务，没有出库任务，给机械手发拆垛指令

							}
						}
					}


					#endregion

					#region 监控扫码

					if (scan?.Value == 1 && SJob?.Value == 0)
					{
						var unloadMission = position.BelongDevice?.Operation.ReadInt32("418");
						var key = barcode.Query().FirstOrDefault(x => x.NewJobNumbell == unloadMission?.Value);
						var resty = mat.Query().FirstOrDefault(x => x.Palletnumber == key.PalletNumber && x.MaterialNumber == key.MaterialNamber);
						var list = TcpClientReadCode.CodeMessage;

						if (list != null)
						{
							foreach (var item in list)
							{
								logger.LogInformation($"当前获取条码信息：{item.Value}");
								if (item.Value != null)
								{
									var info = item.Value.Substring(0, item.Value.Length);
									var numbell = new UniqueNumberGenerator();
									if (!string.IsNullOrEmpty(info) && !info.Contains("NOREAD"))
									{
										if (resty.MaterialName == "183非SE-副栅172背栅200-东磁")
										{
											if (info.Contains("D1"))
											{
												var boxmodel = new BOX
												{
													Id = DateTime.Now.ToString("yyyyMMddHHmmss"),
													MaterialNumber = numbell.GenerateUniqueNumber(),
													MaterialName = "183非SE-副栅172背栅200-东磁",
													MaterialColor = info.Substring(28, 2),
													MaterialGrade = info.Substring(32, 1),
													MaterialVoltage = "",
													MaterialEfficiency = info.Substring(14, 5),
													MaterTime = info.Substring(1, 6),
													MaterAum = info.Substring(34, 4),
													CartonSize = info
												};
												var isok = await PutStorage(boxmodel);
												if (isok)
												{
													list.Clear();
												}

												#region 散库单箱入

												if (boxmodel != null)
												{
													var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
													var res = a?.BelongDevice.Operation.ReadInt16("730");
													var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
													if (res != null && res.Value == 1)
													{
														a?.BelongDevice.Operation.Write("732", (short)21001);
														a?.BelongDevice.Operation.Write("734", (short)time);
													}
												}
												#endregion
											}
											else
											{
												var boxmodel = new BOX
												{
													Id = DateTime.Now.ToString("yyyyMMddHHmmss"),
													MaterialNumber = numbell.GenerateUniqueNumber(),
													MaterialName = "183非SE-副栅172背栅200-东磁",
													MaterialColor = info.Substring(28, 1),
													MaterialGrade = info.Substring(31, 1),
													MaterialVoltage = "",
													MaterialEfficiency = info.Substring(14, 5),
													MaterTime = info.Substring(1, 6),
													MaterAum = info.Substring(33, 4),
													CartonSize = info
												};
												var isok = await PutStorage(boxmodel);
												if (isok)
												{
													list.Clear();
												}

												#region 散库单箱入

												if (boxmodel != null)
												{
													var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
													var res = a?.BelongDevice.Operation.ReadInt16("730");
													var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
													if (res != null && res.Value == 1)
													{
														a?.BelongDevice.Operation.Write("732", (short)21001);
														a?.BelongDevice.Operation.Write("734", (short)time);
													}
												}
												#endregion
											}
										}
										else if (resty.MaterialName == "210非SE-副栅168背栅210-英发公版图形-降3档")
										{
											var boxmodel = new BOX
											{
												Id = DateTime.Now.ToString("yyyyMMddHHmmss"),
												MaterialNumber = numbell.GenerateUniqueNumber(),
												MaterialName = "210非SE-副栅168背栅210-英发公版图形-降3档",
												MaterialColor = info.Substring(51, 2),
												MaterialGrade = info.Substring(32, 1),
												MaterialVoltage = info.Substring(41, 1),
												MaterialEfficiency = info.Substring(34, 6),
												MaterTime = info.Substring(1, 10),
												MaterAum = info.Substring(54, 4),
												CartonSize = info
											};
											var isok = await PutStorage(boxmodel);
											if (isok)
											{
												list.Clear();
											}

											#region 散库单箱入

											if (boxmodel != null)
											{
												var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
												var res = a?.BelongDevice.Operation.ReadInt16("730");
												var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
												if (res != null && res.Value == 1)
												{
													a?.BelongDevice.Operation.Write("732", (short)21001);
													a?.BelongDevice.Operation.Write("734", (short)time);
												}
											}
											#endregion
										}
										else if (resty.MaterialName == "183非SE-副栅172背栅200-天合")
										{
											var boxmodel = new BOX
											{
												Id = DateTime.Now.ToString("yyyyMMddHHmmss"),
												MaterialNumber = numbell.GenerateUniqueNumber(),
												MaterialName = "183非SE-副栅172背栅200-天合",
												MaterialColor = info.Substring(42, 2),
												MaterialGrade = info.Substring(31, 1),
												MaterialVoltage = "",
												MaterialEfficiency = info.Substring(32, 4),
												MaterTime = info.Substring(1, 6),
												MaterAum = info.Substring(27, 4),
												CartonSize = info
											};
											var isok = await PutStorage(boxmodel);
											if (isok)
											{
												list.Clear();
											}

											#region 散库单箱入

											if (boxmodel != null)
											{
												var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
												var res = a?.BelongDevice.Operation.ReadInt16("730");
												var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
												if (res != null && res.Value == 1)
												{
													a?.BelongDevice.Operation.Write("732", (short)21001);
													a?.BelongDevice.Operation.Write("734", (short)time);
												}
											}
											#endregion
										}
										else if (resty.MaterialName == "183非SE-副栅172背栅200-隆基")
										{
											var boxmodel = new BOX
											{
												Id = DateTime.Now.ToString("yyyyMMddHHmmss"),
												MaterialNumber = numbell.GenerateUniqueNumber(),
												MaterialName = "183非SE-副栅172背栅200-隆基",
												MaterialColor = info.Substring(47, 1),
												MaterialGrade = info.Substring(28, 1),
												MaterialVoltage = info.Substring(37, 1),
												MaterialEfficiency = info.Substring(30, 6),
												MaterTime = info.Substring(1, 10),
												MaterAum = info.Substring(49, 4),
												CartonSize = info
											};
											var isok = await PutStorage(boxmodel);
											if (isok)
											{
												list.Clear();
											}

											#region 散库单箱入

											if (boxmodel != null)
											{
												var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
												var res = a?.BelongDevice.Operation.ReadInt16("730");
												var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
												if (res != null && res.Value == 1)
												{
													a?.BelongDevice.Operation.Write("732", (short)21001);
													a?.BelongDevice.Operation.Write("734", (short)time);
												}
											}
											#endregion
										}
										else if (resty.MaterialName == "183非SE-副栅172背栅200-晶澳")
										{
											var boxmodel = new BOX
											{
												Id = DateTime.Now.ToString("yyyyMMddHHmmss"),
												MaterialNumber = numbell.GenerateUniqueNumber(),
												MaterialName = "183非SE-副栅172背栅200-晶澳",
												MaterialColor = info.Substring(42, 2),
												MaterialGrade = info.Substring(31, 1),
												MaterialVoltage = "",
												MaterialEfficiency = info.Substring(32, 4),
												MaterTime = info.Substring(1, 6),
												MaterAum = info.Substring(27, 4),
												CartonSize = info
											};
											var isok = await PutStorage(boxmodel);
											if (isok)
											{
												list.Clear();
											}

											#region 散库单箱入

											if (boxmodel != null)
											{
												var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
												var res = a?.BelongDevice.Operation.ReadInt16("730");
												var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
												if (res != null && res.Value == 1)
												{
													a?.BelongDevice.Operation.Write("732", (short)21001);
													a?.BelongDevice.Operation.Write("734", (short)time);
												}
											}
											#endregion
										}
									}
									break;
								}
							}
						}
					}

					#endregion

					#region 码垛位置状态监控
					//1.检查是否有托盘
					//2.码垛位置有托盘，到2.1，没有托盘到2.2
					if (loadRes != null && loadRes?.Value == 1)
					{
						//2.1
						if (loadMissionRes != null && loadMissionRes.Value != 2)
						{
							var materialType = GetMaterialTypeByMission(loadMissionRes.Value, 3);
							if (materialType != null)
							{
								var res = position.BelongDevice?.Operation.ReadInt16("450");
								var Wan = position.BelongDevice?.Operation.ReadInt16("3720");
								var Fan = position.BelongDevice?.Operation.ReadInt16("3722");
								if (Wan != null && Wan.Value != 0)
								{
									var bell = barcode.Query().FirstOrDefault(x => x.PalletNumber == materialType.PalletNumber);
									if (bell != null)
									{
										bell.type = 0;
										var isOk = barcode.Update(bell);
										if (isOk)
										{
											position.BelongDevice?.Operation.Write("3715", (short)0);
											position.BelongDevice?.Operation.Write("3716", (short)0);
											position.BelongDevice?.Operation.Write("3718", (short)0);
										}
									}
								}
							}

							//整托盘送到缠绕位，空托盘继续在这等码垛
							if (materialType != null && materialType.type == MaterialType.zhengtuo)
							{
								logger.LogInformation($"任务号：{loadMissionRes},得到物料类型：{JsonConvert.SerializeObject(materialType)}");
								//送到缠绕位
								logger.LogInformation($"任务号：{loadMissionRes},得到物料类型：{JsonConvert.SerializeObject(materialType)},送到缠绕位");
								position.BelongDevice?.Operation.Write("452", (short)11007);
								var newJobNumber = NewJobNumber(loadMissionRes.Value);
								if (newJobNumber > 0)
								{
									var isOk = position.BelongDevice?.Operation.Write("454", (short)newJobNumber);
								}
								//loadCheck = false;
							}
						}
					}
					else if (loadRes?.Value == 2 && loadMissionRes != null)
					{
						//2.2 先看缓存位是否有空托盘，有空托盘，从缓存位调空托盘，没有的话，到2.2.1
						if (loadBuffer1Res?.Value == 1 && loadBuffer1MissionRes != null && loadBuffer1MissionRes.Value != 0)
						{
							//从空托盘缓存送到码垛位
							logger.LogInformation($"任务号：{loadBuffer1MissionRes.Value},空托盘缓存送到码垛位");
							position.BelongDevice?.Operation.Write("462", (short)11046);
							var newJobNumber = NewJobNumber(loadBuffer1MissionRes.Value);
							if (newJobNumber > 0)
							{
								position.BelongDevice?.Operation.Write("464", (short)newJobNumber);
							}
							//loadCheck = false;
						}
						else
						{
							//2.2.1 生成一条空托盘出料任务
							logger.LogInformation($"任务号：{loadMissionRes},空托盘出料任务");
							positionInOut?.BelongDevice.Operation.Write("382", (short)11046);
							var newJobNumber = NewJobNumber(loadMissionRes.Value);
							if (newJobNumber > 0)
							{
								position.BelongDevice?.Operation.Write("384", (short)newJobNumber);
							}
							//loadCheck = false;
						}
					}
					#endregion

					#region 单箱出库

					if (dan != null && dan.Value != 2)
					{
						var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
						position.BelongDevice?.Operation.Write("532", (short)21027);
						position.BelongDevice?.Operation.Write("534", (short)time);
					}

					#endregion
				}
			}
			catch (Exception ex)
			{
				logger.LogError($"Error inserting data: {ex.Message}");
			}
			//    Thread.Sleep(5000);
			//}
		}

		#region 通过料口获取设备是否在线

		/// <summary>
		/// 设备编号获取设备是否在线
		/// </summary>
		/// <param name="deviceId"></param>
		/// <returns></returns>
		private bool DeviceIsConned(string deviceId)
		{
			var isOk = false;
			try
			{
				if (!string.IsNullOrEmpty(deviceId))
				{
					var deviceInfo = _deviceManager.Devices.FirstOrDefault(i => i.Id == deviceId && i.Enable);
					if (deviceInfo != null && deviceInfo.IsConnected)
					{
						isOk = true;
					}
				}
			}
			catch (Exception ex)
			{
				logger.LogInformation($"设备不在线");
			}

			return isOk;
		}

		#endregion

		#region 获取任务信息

		/// <summary>
		/// 获取任务信息
		/// </summary>
		/// <param name="Mission">新、旧任务号</param>
		/// <param name="palletNumber">托盘号</param>
		/// <param name="state">状态</param>
		/// 状态解释
		///     0：任务号，托盘号，未完成状态获取信息
		///     1：任务号，托盘号，完成状态获取信息
		///     2：托盘号，完成状态获取信息
		///     3：任务号，完成状态获取信息
		/// <returns></returns>
		private Types GetMaterialTypeByMission(int Mission, int state = 0, string palletNumber = null)
		{
			var missionInfo = new Types();
			switch (state)
			{
				case 0:
					{
						logger.LogInformation($"00000000");
						var list = barcode.Query();
						missionInfo = list.FirstOrDefault(x => x.NewJobNumbell == Mission || x.JobNumbell == Mission && x.PalletNumber == palletNumber && !x.IsComplete);
						if (missionInfo != null)
						{
							return missionInfo;
						}

						break;
					}
				case 1:
					{
						logger.LogInformation($"111111111");
						var list = barcode.Query();
						missionInfo = list.FirstOrDefault(x => x.NewJobNumbell == Mission || x.JobNumbell == Mission && x.PalletNumber == palletNumber && x.IsComplete);
						if (missionInfo != null)
						{
							return missionInfo;
						}

						break;
					}
				case 2:
					{
						logger.LogInformation($"222222");
						var list = barcode.Query();
						missionInfo = list.FirstOrDefault(x => x.PalletNumber == palletNumber && x.IsComplete);
						if (missionInfo != null)
						{
							return missionInfo;
						}

						break;
					}
				default:
					{
						logger.LogInformation($"33333");
						var list = barcode.Query();
						missionInfo = list.FirstOrDefault(x => x.NewJobNumbell == Mission || x.JobNumbell == Mission && x.IsComplete);
						if (missionInfo != null)
						{
							return missionInfo;
						}

						break;
					}
			}
			return missionInfo;
		}

		#endregion

		private Siterelease ProccStation(string podid)
		{
			var list = sit.Query();
			var Procc = new Siterelease();
			if (!string.IsNullOrEmpty(podid))
			{
				Procc = list.FirstOrDefault(x => x.podID == podid && x.occupyStatus == 3);
				if (Procc != null)
				{
					if (Procc.occupyStatus == 3)
					{
						return Procc;
					}
				}
			}
			return Procc;
		}

		private int NewJobNumber(int jonNumber, string palletNumber = null)
		{
			using var db = lifetimeScope.BeginLifetimeScope().Resolve<ISqlSugarClient>().CopyNew();
			if (jonNumber > 0)
			{
				// jonNumber + 1
				int count = new Random().Next(1000, 9999);
				var newJobNamber = count;
				var job = db.Queryable<Types>().First(x => x.NewJobNumbell == jonNumber || x.JobNumbell == jonNumber && x.PalletNumber == palletNumber);
				if (job != null)
				{
					job.NewJobNumbell = newJobNamber;
					job.IsComplete = true;
					db.Updateable(job).UpdateColumns(i => new { i.NewJobNumbell, i.IsComplete }).ExecuteCommand();
					return newJobNamber;
				}
			}
			else
			{
				int count = new Random().Next(1000, 9999);
				var newJobNumber = count;
				var job = db.Queryable<Types>().First(x => x.NewJobNumbell == jonNumber && x.PalletNumber == palletNumber);
				if (job != null)
				{
					job.NewJobNumbell = newJobNumber;
					job.IsComplete = true;
					db.Updateable(job).UpdateColumns(i => new { i.NewJobNumbell, i.IsComplete }).ExecuteCommand();
					return newJobNumber;
				}
			}

			return 0;
		}

		#region

		#region 出入库口

		/// <summary>
		/// 出入库口
		/// </summary>
		/// <returns></returns>
		private void OutOrPutPort(TransferPort portInfo, int onePutStorage)
		{
			try
			{
				logger.LogInformation($"出入库口，portInfo:{portInfo?.Palletnumber},onePutStorage：{onePutStorage}");
				if (portInfo != null && portInfo.CurrentNumber > 0 && !string.IsNullOrEmpty(portInfo.Palletnumber) && onePutStorage == 1)
				{
					logger.LogInformation($"出入库口，料口中的物料编号：{portInfo.Palletnumber}");
					var sty1 = spat.Query().FirstOrDefault(x => x.desStationCodes == "A1036" && x.Palletnumber == portInfo.Palletnumber);
					logger.LogInformation($"出入库口，sty1：{sty1?.desType},podID:{sty1?.podID}");
					var redatPort = port.Query().FirstOrDefault(x => x.podID == sty1?.podID && x.desType == sty1?.desType && x.status == 4);
					logger.LogInformation($"出入库口，redatPort：{redatPort?.desType},podID:{redatPort?.podID}");
					logger.LogInformation($"出入库口位置：{portInfo?.Id}");
					var positionInOutMissionRes = portInfo?.BelongDevice.Operation.ReadInt32("378");
					logger.LogInformation($"出入库口位置：上报任务号：{positionInOutMissionRes?.Value}");
					if (redatPort != null && redatPort.messageType == 10 && redatPort.status == 4 && positionInOutMissionRes != null)
					{
						var jobInfo = barcode.Query().FirstOrDefault(x => x.RobotJobCode == redatPort.podID);
						var numbell = GetMaterialTypeByMission(positionInOutMissionRes.Value, 1, jobInfo.PalletNumber);
						if (numbell != null && sty1 != null)
						{
							logger.LogInformation($"111111任务号：" + $"{positionInOutMissionRes?.Value}");
							//送到缠绕膜
							var newJobNumber = NewJobNumber(numbell.NewJobNumbell, numbell.PalletNumber);
							var outOrPusStorageState = portInfo.BelongDevice.Operation.ReadInt16("376");
							if (outOrPusStorageState.Value == 0)
							{
								logger.LogInformation($"当前线体任务状态为：{outOrPusStorageState.Value}");
								portInfo?.BelongDevice.Operation.Write("374", (short)newJobNumber);
								var jobNumber = portInfo?.BelongDevice.Operation.ReadInt32("378");
								if (jobNumber?.Value == 0)
								{
									portInfo?.BelongDevice.Operation.Write("372", (short)11007);
									Thread.Sleep(2000);
									portInfo?.BelongDevice.Operation.Write("374", (short)newJobNumber);
								}
								portInfo.CurrentNumber = 0;
								portInfo.Palletnumber = string.Empty;
								_transferPort.Context.Updateable(portInfo).UpdateColumns(i => new { i.CurrentNumber, i.Palletnumber }).ExecuteCommand();
								var Cont = new ContainerDTO
								{
									warehouseID = "HETU",
									requestID = "86f3ebf3-1ba4-4ccc1",
									clientCode = "WCS",
									stationCode = "A1036",
								};
								TES.releaseStation(Cont);
							}
							else
							{
								logger.LogInformation($"当前线体任务状态为：{outOrPusStorageState.Value}");
								portInfo?.BelongDevice.Operation.Write("3711", (short)1);
								portInfo.CurrentNumber = 0;
								portInfo.Palletnumber = string.Empty;
								_transferPort.Context.Updateable(portInfo).UpdateColumns(i => new { i.CurrentNumber, i.Palletnumber }).ExecuteCommand();
								var Cont = new ContainerDTO
								{
									warehouseID = "HETU",
									requestID = "86f3ebf3-1ba4-4ccc1",
									clientCode = "WCS",
									stationCode = "A1036",
								};
								TES.releaseStation(Cont);
							}


						}
					}
				}
				else
				{
					logger.LogInformation($"出入库口方法进到else");
					//2.判断料口的料是进料还是出料，进料，跳过，出料，到第3步
					//很重要，要判断任务类型，还没有做，加上
					#region
					var missionRes1 = portInfo?.BelongDevice.Operation.ReadInt32("378");
					logger.LogInformation($"读取当前线体任务号：{missionRes1.Value}");
					if (missionRes1.Value != 0)
					{
						// positionLoad?.BelongDevice.Operation.Write("352", (short)11036);
						var Station = new FeederSitesDTO
						{
							warehouseID = "HETU",
							requestID = "86f3ebf3-1ba4-4ccc1",
							clientCode = "WCS",
							stationCode = "A1036",
						};
						TES.preOccupyStation(Station);
						var Station1 = new FeederSites
						{
							warehouseID = Station.warehouseID,
							requestID = Station.requestID,
							clientCode = Station.clientCode,
							stationCode = Station.stationCode,
						};
						feed.Add(Station1);
						//var model = new SalverDTO
						//{
						//    warehouseID = "HETU",
						//    requestID = "86f3ebf3-1ba4-4ccc1",
						//    clientCode = "WCS",
						//    stationCode = "A1036",
						//    layoutID = "513611347175407640",
						//};
						var salmodel = new Salver
						{
							warehouseID = "HETU",
							requestID = "86f3ebf3-1ba4-4ccc1",
							clientCode = "WCS",
							stationCode = "A1036",
							podID = DateTime.Now.ToString("ddHHss"),
							layoutID = "513611347175407640",
						};
						var numbell = GetMaterialTypeByMission(missionRes1.Value);
						if (string.IsNullOrEmpty(numbell.RobotJobCode))
						{
							numbell.RobotJobCode = salmodel.podID;
							barcode.Context.Updateable(numbell).UpdateColumns(i => new { i.RobotJobCode }).ExecuteCommand();
							sal.Add(salmodel);
						}

						var slverInfo = sal.Query().FirstOrDefault(i => i.podID == numbell.RobotJobCode);
						if (slverInfo != null)
						{
							TES.occupyStation(slverInfo);
							var bulkInfor = new AssignStorageViewModel
							{
								MaterialNamber = numbell.MaterialNamber
							};

							var lister = barcode.Query().Where(x => x.NewJobNumbell == missionRes1.Value).FirstOrDefault();
							var materialinfo = mat.Query().FirstOrDefault(i => i.MaterialNumber == lister?.MaterialNamber);
							var sty = new WareHouse();
							if (string.IsNullOrEmpty(materialinfo?.StorageId))
							{
								//sty = await AssignStorage(bulkInfor);
							}
							else
							{
								sty = hous.Query().FirstOrDefault(x => x.MaterialNamber == materialinfo?.MaterialNumber);
							}
							if (sty != null)
							{
								var model1 = new IanewayDTO
								{
									warehouseID = "HETU",
									requestID = "86f3ebf3-1ba4-4ccc1",
									clientCode = "WCS",
									desType = locations.StorageLocation,
									srcType = 1,
									podID = slverInfo.podID,
									priority = 3,
									bizID = DateTime.Now.ToString("ddHHss") + 1,
									replacePodTask = 0,
									desExt = new Dictionary<string, int>()
												{
													 { "unload",1 }
												},
									desStorageID = sty.CrownPrincce,
								};
								TES.newMovePodTask(model1);
								var anemodel = new Ianeway
								{
									warehouseID = model1.warehouseID,
									requestID = model1.requestID,
									clientCode = model1.clientCode,
									desType = model1.desType,
									srcType = 1,
									podID = model1.podID,
									priority = model1.priority,
									bizID = model1.bizID,
									replacePodTask = model1.replacePodTask,
									desExt = JsonConvert.SerializeObject(model1.desExt),
									desStorageID = model1.desStorageID,
								};
								var informate = barcode.Query().Where(x => x.NewJobNumbell == missionRes1.Value).FirstOrDefault();
								var inform = ProccStation(!string.IsNullOrEmpty(informate?.RobotJobCode) ? informate.RobotJobCode : string.Empty);
								if (inform != null && inform.occupyStatus == 3)
								{
									portInfo?.BelongDevice.Operation.Write("3712", (short)1);
									var Cont = new ContainerDTO
									{
										warehouseID = "HETU",
										requestID = "86f3ebf3-1ba4-4ccc1",
										clientCode = "WCS",
										stationCode = "A1036",
									};
									TES.releaseStation(Cont);
								}
							}
						}
					}
					//else
					//{
					//	//3.判断物料状态，是整托（3.1），还是散托（3.1），还是空托盘（3.2）
					//	var materialType = GetMaterialTypeByMission(positionInOutMissionRes.Value);
					//	if (materialType != null && materialType.type == MaterialType.three)
					//	{
					//		logger.LogInformation($"任务号：{positionInOutMissionRes},得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//		//1.判断码垛位置&空托盘缓存位置是否有料，全部没有料，送到码垛位
					//		if (loadRes?.Value == 2 && loadBuffer1Res?.Value == 2)
					//		{
					//			logger.LogInformation($"任务号：" +
					//				$"{positionInOutMissionRes},码垛位置&空托盘缓存位置是否有料，全部没有料，送到码垛位,得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//			//送去码垛位置，当前任务不用继续检查
					//			positionInOut?.BelongDevice.Operation.Write("372", (short)11046);
					//			var newJobNumber = NewJobNumber(positionInOutMissionRes.Value);
					//			if (newJobNumber > 0)
					//			{
					//				position1?.BelongDevice.Operation.Write("374", (short)newJobNumber);
					//			}
					//		}
					//		//2.码垛位置有料，判断缓存位是否有空余，有空余，送到缓存位
					//		else if (loadRes?.Value == 1 && loadBuffer1Res?.Value == 2)
					//		{
					//			//送去空托盘缓存位置

					//			//if()
					//			//{
					//			//    positionInOut?.BelongDevice.Operation.Write("372", (short)11005);
					//			//}
					//			//else
					//			//{
					//			//    
					//			//}

					//			logger.LogInformation($"任务号：" +
					//				$"{positionInOutMissionRes},码垛位置有料，缓存位有空余，送到缓存位,得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//			positionInOut?.BelongDevice.Operation.Write("372", (short)11047);
					//			var newJobNumber = NewJobNumber(positionInOutMissionRes.Value);
					//			if (newJobNumber > 0)
					//			{
					//				position1?.BelongDevice.Operation.Write("374", (short)newJobNumber);
					//			}
					//		}
					//	}
					//	//3.1 出整托和散托，送到撕缠绕膜位置
					//	else
					//	{

					//		logger.LogInformation($"任务号：" +
					//			$"{positionInOutMissionRes},出整托和散托，送到撕缠绕膜位置,得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//		//送到缠绕膜
					//		positionInOut?.BelongDevice.Operation.Write("372", (short)11007);
					//		var newJobNumber = NewJobNumber(positionInOutMissionRes.Value);
					//		if (newJobNumber > 0)
					//		{
					//			position1?.BelongDevice.Operation.Write("374", (short)newJobNumber);
					//		}
					//	}
					//}
					#region
					//if (positionInOut != null && positionInOutMissionRes != null && positionInOutMissionRes.Value != 0)
					//{
					//	//如果任务变了，或者上次检查没有过
					//	if (positionInOutMission != positionInOutMissionRes.Value || positionInOutCheck)
					//	{
					//		//3.判断物料状态，是整托（3.1），还是散托（3.1），还是空托盘（3.2）
					//		var materialType = GetMaterialTypeByMission(positionInOutMissionRes.Value);
					//		if (materialType != null && materialType.type == MaterialType.three)
					//		{
					//			logger.LogInformation($"任务号：{positionInOutMissionRes},得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//			//1.判断码垛位置&空托盘缓存位置是否有料，全部没有料，送到码垛位
					//			if (loadRes?.Value == 2 && loadBuffer1Res?.Value == 2)
					//			{
					//				logger.LogInformation($"任务号：" +
					//					$"{positionInOutMissionRes},码垛位置&空托盘缓存位置是否有料，全部没有料，送到码垛位,得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//				//送去码垛位置，当前任务不用继续检查
					//				positionInOut?.BelongDevice.Operation.Write("372", (short)11046);
					//				var newJobNumber = NewJobNumber(positionInOutMissionRes.Value);
					//				if (newJobNumber > 0)
					//				{
					//					position1?.BelongDevice.Operation.Write("374", (short)newJobNumber);
					//				}


					//			}
					//			//2.码垛位置有料，判断缓存位是否有空余，有空余，送到缓存位
					//			else if (loadRes?.Value == 1 && loadBuffer1Res?.Value == 2)
					//			{
					//				//送去空托盘缓存位置

					//				//if()
					//				//{
					//				//    positionInOut?.BelongDevice.Operation.Write("372", (short)11005);
					//				//}
					//				//else
					//				//{
					//				//    
					//				//}

					//				logger.LogInformation($"任务号：" +
					//					$"{positionInOutMissionRes},码垛位置有料，缓存位有空余，送到缓存位,得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//				positionInOut?.BelongDevice.Operation.Write("372", (short)11047);
					//				var newJobNumber = NewJobNumber(positionInOutMissionRes.Value);
					//				if (newJobNumber > 0)
					//				{
					//					position1?.BelongDevice.Operation.Write("374", (short)newJobNumber);
					//				}
					//			}
					//		}
					//		//3.1 出整托和散托，送到撕缠绕膜位置
					//		else
					//		{
					//			logger.LogInformation($"任务号：" +
					//				$"{positionInOutMissionRes},出整托和散托，送到撕缠绕膜位置,得到物料类型：{JsonConvert.SerializeObject(materialType)}");
					//			//送到缠绕膜
					//			positionInOut?.BelongDevice.Operation.Write("372", (short)11007);
					//			var newJobNumber = NewJobNumber(positionInOutMissionRes.Value);
					//			if (newJobNumber > 0)
					//			{
					//				position1?.BelongDevice.Operation.Write("374", (short)newJobNumber);
					//			}
					//		}
					//	}
					//}
					#endregion
					#endregion
				}
			}
			catch (Exception ex)
			{
				logger.LogInformation($"出入库口抛异常，异常信息：{ex.Message}");
			}
		}

		#endregion


		//机械臂拆
		public async Task<dynamic> Conveyor(int id, int type)
		{
			//    var transferPortInfo = await _transferPort.QueryAsync();
			var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
			var res = a?.BelongDevice.Operation.ReadInt16("410");
			logger.LogInformation($"告诉机械臂的类型{id},数量{type}");
			if (id == 1 && res != null && res.Value != 0)
			{
				var Fan = a?.BelongDevice.Operation.ReadInt16("3721");
				var Wan = a?.BelongDevice.Operation.ReadInt16("3719");
				logger.LogInformation($"机械臂的反馈{Fan},完成信号{Wan.Value}");
				if (Wan != null && Wan.Value == 1)
				{
					a?.BelongDevice.Operation.Write("3713", (short)0);
					a?.BelongDevice.Operation.Write("3717", (short)0);
				}
				else
				{
					a?.BelongDevice.Operation.Write("3713", (short)1);
					a?.BelongDevice.Operation.Write("3717", (short)type);
				}
			}
			else if (id == 2 && res != null && res.Value != 0)
			{
				var res2 = a?.BelongDevice.Operation.ReadInt16("3721");
				var res1 = a?.BelongDevice.Operation.ReadInt16("3719");
				logger.LogInformation($"机械臂的反馈{res2.Value},完成信号{res1.Value}");
				if (res1 != null && res1.Value == 1)
				{
					a?.BelongDevice.Operation.Write("3714", (short)0);
					a?.BelongDevice.Operation.Write("3717", (short)0);
				}
				else
				{
					a?.BelongDevice.Operation.Write("3714", (short)1);
					a?.BelongDevice.Operation.Write("3717", (short)type);
				}
			}

			return ApiResultHelp.Success("成功");
		}

		//机械臂码
		public async Task<dynamic> Stacking(int id, int type)
		{
			var transferPortInfo = await _transferPort.QueryAsync();
			var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
			var res = a?.BelongDevice.Operation.ReadInt16("450");
			if (id == 1 && res != null && res.Value == 1)
			{
				var Wan = a?.BelongDevice.Operation.ReadInt16("3720");
				var Fan = a?.BelongDevice.Operation.ReadInt16("3722");
				if (Wan != null && Wan.Value != 0)
				{
					a?.BelongDevice.Operation.Write("3715", (short)0);
					a?.BelongDevice.Operation.Write("3718", (short)0);
					return 0;
				}
				else if (Fan != null && Fan.Value == 0 && Wan.Value == 0)
				{
					a?.BelongDevice.Operation.Write("3715", (short)1);
					a?.BelongDevice.Operation.Write("3718", (short)type);
				}
			}
			else if (id == 2 && res != null && res.Value == 1)
			{

				var res1 = a?.BelongDevice.Operation.ReadInt16("3720");
				var res2 = a?.BelongDevice.Operation.ReadInt16("3722");
				if (res1 != null && res1.Value != 0)
				{
					a?.BelongDevice.Operation.Write("3716", (short)0);
					a?.BelongDevice.Operation.Write("3718", (short)0);
					return 0;
				}
				else if (res2 != null && res2.Value == 0 && res1.Value == 0)
				{
					a?.BelongDevice.Operation.Write("3716", (short)1);
					a?.BelongDevice.Operation.Write("3718", (short)type);
				}
			}
			return true;
		}


		//一期入库
		public async Task<bool> Job1(int numbell)
		{
			var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");

			var res = a?.BelongDevice.Operation.ReadInt16("100");
			if (res != null && res.Value != 0)
			{
				var result1 = a?.BelongDevice.Operation.Write("102", (short)11007);
				var result2 = a?.BelongDevice.Operation.Write("104", (short)numbell);
				if (result1 != null && result1.IsSucceed && result2 != null && result2.IsSucceed)
				{
					return true;
				}
			}
			//var res1 = a?.BelongDevice.Operation.ReadInt16("106");
			//var res2 = a?.BelongDevice.Operation.ReadInt16("107");
			//var dy = a?.BelongDevice.Operation.ReadInt32("108");
			//if (res1.Value==1 && res2.Value==2 && dy.Value==numbell)
			//{
			//    return ApiResultHelp.Success("成功");
			//}
			return false;

		}
		/// <summary>
		/// 入库
		/// </summary>
		/// <param name="numbell">任务号</param>
		/// <param name="type">类型</param> 1,2,3,4
		/// <returns></returns>
		public async Task<bool> Job2(int numbell, int type)
		{
			var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");//(11062)
			var res1 = a?.BelongDevice.Operation.ReadInt16("490");
			//var res2 = a?.BelongDevice.Operation.ReadInt16("521");
			if (res1 != null && res1.Value != 0)
			{
				if (type == 1 || type == 2 || type == 3)
				{
					a?.BelongDevice.Operation.Write("492", (short)11041);
					a?.BelongDevice.Operation.Write("494", (short)numbell);
					return true;
				}
				else
				{
					a?.BelongDevice.Operation.Write("492", (short)11027);
					a?.BelongDevice.Operation.Write("494", (short)numbell);
					return true;

				}
			}
			return false;
		}

		//堆垛机
		public string BulkPutStorage(BulkStorage model)
		{
			try
			{
				var handler = new HttpClientHandler();
				handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls11;
				var httpclient = new HttpClient(handler);

				httpclient.DefaultRequestHeaders.Accept.Clear();
				httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

				HttpContent httpContent = JsonContent.Create(model, typeof(BulkStorage), MediaTypeHeaderValue.Parse("application/json"), new System.Text.Json.JsonSerializerOptions()
				{
					Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Default
				});

				HttpResponseMessage repsone = httpclient.PostAsync("http://10.6.3.1:9098/api/Material/CreateMaterial", httpContent).Result;
				if (repsone.IsSuccessStatusCode)
				{
					Task<string> t = repsone.Content.ReadAsStringAsync();
					if (t != null)
					{
						return t.Result;
					}
				}
				return string.Empty;
			}
			catch (Exception ex)
			{
				logger.LogError($"Error info: {ex.Message}");
			}

			return string.Empty;
		}

		//单箱出库
		public dynamic BulkInformation(BulkInformationViewModel bulkInformation)
		{
			var isOk = false;
			try
			{
				logger.LogInformation($"收到调用消息：{JsonConvert.SerializeObject(bulkInformation)}");
				var list = box.Query().FirstOrDefault(x => x.MaterialNumber == bulkInformation.MaterialNumber);
				if (list != null)
				{
					list.Outbound = true;
					isOk = box.Update(list);
					//var materialList = new List<string>();
					//if (isOk)
					//{
					//    materialList.Add(list.MaterialNumber);
					//    if (materialList.Count > 0)
					//    {
					//        foreach (var item in materialList.ToList())
					//        {
					//            var outStoragePort = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
					//            var res = outStoragePort?.BelongDevice.Operation.ReadInt16("530");
					//            logger.LogInformation($"处理物料：{bulkInformation.MaterialNumber}，当前530点位值：{res?.Value}");
					//            var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
					//            if (res is not { Value: 1 }) continue;
					//            var result1 = outStoragePort?.BelongDevice.Operation.Write("532", (short)21027);
					//            var result2 = outStoragePort?.BelongDevice.Operation.Write("534", (short)time);
					//            logger.LogInformation($"下发分路号是否成功：{JsonConvert.SerializeObject(result1)}任务号是否写成功：{JsonConvert.SerializeObject(result2)}");
					//            if (result1 is not { IsSucceed: true } || result2 is not { IsSucceed: true }) continue;
					//            logger.LogInformation($"清楚的数据: {item}");
					//            materialList.Remove(item);
					//        }
					//    }
					//}
				}
			}
			catch (Exception ex)
			{
				logger.LogError($"error info:{ex.Message}");
			}
			return isOk;
		}

		#endregion

		//分配库位
		public async Task<WareHouse> AssignStorage(AssignStorageViewModel assignStorage)
		{
			var storage = new WareHouse();
			try
			{
				var db = lifetimeScope.BeginLifetimeScope().Resolve<ISqlSugarClient>().CopyNew();
				storage = await db.Queryable<WareHouse>().Where(i => i.Enable && !i.IsFull && i.CurrentQuantity == 0).FirstAsync();
				var material = await db.Queryable<Material>().FirstAsync(i => i.MaterialNumber == assignStorage.MaterialNamber);
				if (storage != null && material != null)
				{
					storage.CurrentQuantity++;
					storage.WHStare = true;
					storage.MaterialNamber = material.MaterialNumber;
					storage.MaterialName = material.MaterialName;
					material.StorageId = storage.WHNumber;
					await db.Updateable(storage).ExecuteCommandAsync();
					//await db.Updateable(storage).UpdateColumns(i => new { i.IsFull, i.CurrentQuantity, i.WHStare, i.MaterialNamber, i.MaterialName }).ExecuteCommandAsync();
					await db.Updateable(material).UpdateColumns(i => new { i.StorageId }).ExecuteCommandAsync();
				}
			}
			catch (Exception ex)
			{
				logger.LogError($"分配库位失败，失败信息：{ex.Message}");
			}
			return storage;
		}
		//发送堆垛机信息
		public async Task<bool> PutStorage(BOX box)
		{
			var isOk = false;
			try
			{
				using var db = lifetimeScope.BeginLifetimeScope().Resolve<ISqlSugarClient>().CopyNew();
				var bulkStorage = new BulkStorage
				{
					Id = box.Id,
					MaterialNumber = box.MaterialNumber,
					MaterialName = box.MaterialName,
					MaterialColor = box.MaterialColor,
					MaterialGrade = box.MaterialGrade,
					MaterialVoltage = box.MaterialVoltage,
					MaterialEfficiency = box.MaterialEfficiency,
					MaterialPutPort = "EAEX2",
					MaterialOutPort = "EAEX1",
					MaterialPort = "EA",
				};
				if (bulkStorage != null)
				{
					string li = BulkPutStorage(bulkStorage);
					if (!string.IsNullOrEmpty(li))
					{
						var stacker = JsonConvert.DeserializeObject<SkackerResult>(li);
						if (stacker != null && stacker.code == "200")
						{
							var count = await db.Insertable<BOX>(box).ExecuteCommandAsync();
							if (count > 0)
							{
								isOk = true;
								logger.LogInformation("Data inserted successfully.");
							}
							else
							{
								logger.LogInformation("Data inserted error.");
							}
						}
						else
						{
							logger.LogInformation($"调用接口失败，失败信息：{JsonConvert.SerializeObject(stacker)}");
						}
					}
					else
					{
						logger.LogInformation($"调用接口失败返回值为空");
					}
				}
			}
			catch (Exception ex)
			{
				logger.LogError($"Error inserting data: {ex.Message}");
			}

			return isOk;
		}
	}
}
